import { Component, Input, Output, EventEmitter, AfterViewInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { WidgetComponent } from '../../models/layout.models';

declare var Chart: any;

@Component({
  selector: 'app-bar-chart-widget',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="component">
      <div class="component-header">
        <div class="component-title">
          <i class="material-icons">bar_chart</i>
          {{widget.title}}
        </div>
        <div class="component-actions">
          <button (click)="onSettings()"><i class="material-icons">settings</i></button>
          <button (click)="onDelete()"><i class="material-icons">delete</i></button>
        </div>
      </div>
      <div class="component-content chart-component">
        <canvas [id]="'barChart-' + widget.id"></canvas>
      </div>
    </div>
  `,
  styleUrls: ['./widgets.component.scss']
})
export class BarChartWidgetComponent implements AfterViewInit {
  @Input() widget!: WidgetComponent;
  @Output() delete = new EventEmitter<void>();

  ngAfterViewInit() {
    setTimeout(() => {
      this.initChart();
    }, 100);
  }

  initChart() {
    const ctx = document.getElementById('barChart-' + this.widget.id);
    if (ctx) {
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['一月', '二月', '三月', '四月', '五月', '六月'],
          datasets: [{
            label: '销售额',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: 'rgba(63, 81, 181, 0.5)',
            borderColor: 'rgba(63, 81, 181, 1)',
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    }
  }

  onSettings() {
    console.log('Settings clicked for widget:', this.widget.id);
  }

  onDelete() {
    this.delete.emit();
  }
}
